/*
 * @Author: sunli
 * @Date: 2024-02-21 10:35:21
 * @LastEditors: sunli
 * @LastEditTime: 2024-02-21 14:41:15
 * @FilePath: /debug-server/router/register.js
 * @Description: 
 */
let express = require('express')
let router = express()
let mongoose = require('mongoose')
let userModel = mongoose.model('user')
router.post('/', async (req, res) => {
  const body = req.body

  // 完整性校验
  if (!body.userName || !body.mobile || !body.email || !body.password) {
    return res.send({code: 0,message: '未完善注册信息'})
  }

  // 重复注册
  const checkName = await userModel.findOne({userName: body.userName})
  if (checkName) {
    return res.send({code: 0, message: '重复校验: 用户名已存在'})
  }
  const checkMobile = await userModel.findOne({mobile: body.mobile})
  if (checkMobile) {
    return res.send({code: 0, message: '重复校验: 手机号码已存在'})
  }
  const checkEmail = await userModel.findOne({email: body.email})
  if (checkEmail) {
    return res.send({code: 0, message: '重复校验: 电子邮箱已存在'})
  }


  const data = new userModel({
    userName: body.userName, // 用户名
    mobile: body.mobile,
    email: body.email,
    password: body.password
  })

  data.save()
    .then(async () => {
      const findUser = await userModel.findOne({userName: body.userName})
      res.send({
        code: 1,
        message: '注册成功',
        resObject: {
          userName: findUser.userName,
          email: findUser.email,
          mobile: findUser.mobile
        }
      })
    })
    .catch(error => {
      res.send({
        code: 0,
        message: '注册失败'
      })
    })
})

module.exports = router
